<?php

class Application_Model_DbTable_TaiKhoan extends Zend_Db_Table_Abstract
{

    protected $_name = 'TAIKHOAN';

    
    public function ajaxLoad( $datas = array() ){
        $select = $this->select();
        
        $select->from(array('tk'=>'TAIKHOAN'))
               ->join(array('nh'=>'NHOMTAIKHOAN'),"tk.MaNhom=nh.MaNhom", array('Nhom'=>'nh.TenNhom'))
               ->order("MaTaiKhoan asc")
               ->setIntegrityCheck(false);
        $table = new stdClass();
        $table->tbody = $this->fetchAll($select)->toArray();
        return $table;
    }
    
    public function ajaxInsert($args){
        if(is_string($args)){
            $term = array();
            parse_str($args,$term );
            $args = $term;
        }
        $table = new stdClass();
        $row = $this->fetchRow($this->select()->where("TenTaiKhoan=?",$args['TenTaiKhoan']));
        if(!$row){
            $row = $this->createRow($args);
            $row->MatKhau = md5($row->MatKhau);
            $id = $row->save();
            $table = $this->ajaxLoad();
        }else{
            $table->message = "Tài khoản đã tồn tại";
        }        
        return $table;
    }
    
    public function ajaxDelete( $args = array() ){
        $row = $this->find($args['MaTaiKhoan'])->current();
        if($row && $row->TenTaiKhoan!="admin") {
             $row->delete();
        }
        $table = new stdClass();
        $table = $this->ajaxLoad();
        return $table;
    }
    
    public function ajaxGetUser($id) {
        $row = $this->find($id)->current();
        return $row->toArray();
    }
    
    public function ajaxEditUser($args){
         if(is_string($args)){
            $term = array();
            parse_str($args,$term );
            $args = $term;
        }
        $mataikhoan = $args['MaTaiKhoan'];
        $row = $this->find($mataikhoan)->current(); 
        foreach($args as $key => $value){
            if( $key=="MatKhau" && $value != "" ){
                $row->{$key} = md5($value);
            }elseif($key != "TenTaiKhoan"){
                $row->{$key} = $value;
            }
        }
        $row->save();
        return $this->ajaxLoad();
    }
}

